<template>
  <!-- 日常任务发布 -->
  <div class="page-padding-bg">

    <div>

      <manager-table :titleOption="titleOption" :tableTopBtn="tableTopBtn" :columns="columns" :dataSource="dataSource" :tableRBtn="tableRBtn" @tableRClick="tableRClick" @tableTopClick="tableTopClick"
        v-model="search1" v-model:search2="search2" @search_btn="search_btn" @resert="resert" :istoolbar="{type:'task',status:true}" @task_tab_change=task_tab_change
        @export_table="export_table"></manager-table>

      <Pagination :currentPage="currentPage" :limit="limit" :total="total" @page_change="page_change"></Pagination>

      <!-- 弹层 -->
      <lay-layer v-model="is_visible" :area="['700px', '500px']" :title="visibleTitle" :btn=" visibleTitle=='查看任务'?'': visible_opteron" resize :shadeClose='false'>
        <div style="padding: 20px 40px 20px 20px;">
          <lay-form ref="layFormRef11" :model="form" required>
            <lay-form-item label="选择烟支" prop="allowanceList">

              <lay-select v-model="form.allowanceList" multiple placeholder="请选择" style="width: 100%;" size="sm" :minCollapsedNum="100" :disabled="visibleTitle=='查看任务'">
                <lay-select-option :value="item.id" :label="item.smokeModel" v-for="item in smokeList" :key="item.id" :disabled="visibleTitle=='查看任务'"></lay-select-option>
              </lay-select>
            </lay-form-item>

            <lay-form-item label="评吸人员" prop="userList">
              <!-- <div v-if="visibleTitle=='查看任务'" class="df ai-c w100 h100" style="height: 38px;">
                <span style="margin-right: 8px;color: #b1b1b1;" v-for="item in form.userList" :key="item">{{get_user_name(item)}}</span>
              </div>
              <lay-select v-else v-model="form.userList" multiple allow-clear placeholder="请选择" style="width: 100%;" size="sm">
                <lay-select-option :value="item.key" :label="item.title" v-for="item in userList1" :key="item.key" :disabled="visibleTitle=='查看任务'"></lay-select-option>
              </lay-select> -->

              <lay-select v-model="form.userList" multiple placeholder="请选择" style="width: 100%;" :minCollapsedNum="100" :disabled="visibleTitle=='查看任务'">
                <!-- <lay-select-option :value="item.id" :label="item.label" v-for="item in judgeList" :key="item.id"></lay-select-option> -->
                <template #header>
                  <div style="padding: 10px">
                    <lay-checkbox v-model="checkboxValue_d" skin="primary" :isIndeterminate="isIndeterminate_d" @change="hanldeChange_d" value="1" :disabled="visibleTitle=='查看任务'">全选</lay-checkbox>
                  </div>
                </template>
                <lay-select-option :value="item.name" :label="item.description" v-for="item in judgeData['0']" :key="item.name" :disabled="visibleTitle=='查看任务'"></lay-select-option>

              </lay-select>
            </lay-form-item>

            <lay-form-item label="评吸时间" prop="meetingTime">
              <!-- <lay-date-picker type="datetime" v-model="form.meetingTime" placeholder="请选择" :disabled="visibleTitle=='查看任务'" style="width: 100%;"></lay-date-picker> -->
              <lay-date-picker v-model="form.meetingTime" simple type="date" placeholder="请选择" style="width: 100%;" :disabled="visibleTitle=='查看任务'"></lay-date-picker>
            </lay-form-item>
          </lay-form>
        </div>
      </lay-layer>

      <!-- 新增周任务 -->
      <lay-layer v-model="is_visible_week" :area="['800px', '500px']" :title="visibleTitle" resize :shadeClose='false' :btn="   visibleTitle=='查看任务'?'':  visible_opteron_week">
        <div style="padding: 20px 40px 20px 20px;" class="week-visible">
          <!-- <el-form :model="form_week" ref="elFormRef11" :rules="rules_week">

            <el-form-item label="选择烟支" prop="allowanceList">

              <el-select v-model="form_week.allowanceList" multiple placeholder="请选择" style="width: 100%;" >
                <el-option class="select-option" :value="item.id" :label="item.smokeModel" v-for="item in smokeList" :key="item.id"> </el-option>
 
                <el-checkbox-group v-model="form_week.allowanceList" @change="check_change_week">
                  <ul class="uu">
                    <li v-for="item in smokeList" :key="item.id" class="df" style="justify-content: left;">
                      <div> <el-checkbox name="like" skin="primary" :value="item.id" style=" width: 100px; padding: 8px 6px;" @click="check_click(item)">
                          <span>{{ item.smokeModel }}</span>
                        </el-checkbox>
                      </div>
                      <div class="df weight ai-c"> <span>烟支重量：</span> <el-input type="number" v-model="item.weight" placeholder="请输入重量/g" /></div>
                      <div class="df data ai-c" style="margin: 0 10px;"> <span>生产日期：</span> <el-input type="text" v-model="item.data" placeholder="格式2020-10-11" /></div>
                    </li>
                  </ul>
                </el-checkbox-group>
              </el-select>


            </el-form-item>
            <el-form-item label="评吸人员" prop="userList">
              <el-input v-model="form_week.userList"></el-input>
            </el-form-item>
            <el-form-item label="记录人" prop="recorder">
              <el-input v-model="form_week.recorder"></el-input>
            </el-form-item>
            <el-form-item label="负责人" prop="header">
              <el-input v-model="form_week.header"></el-input>
            </el-form-item>
            <el-form-item label="评吸时间" prop="meetingTime">
              <el-input v-model="form_week.meetingTime"></el-input>
            </el-form-item>

          </el-form> -->

          <lay-form :model="form_week" ref="elFormRef11" :rules="rules_week" required>
            <lay-form-item label="选择烟支" prop="allowanceList">
              <div class="none-option">
                <lay-select v-model="form_week.allowanceList" multiple placeholder="请选择" style="width: 100%;">
                  <template v-for="item in smokeList" :key="item.id">
                    <lay-select-option v-if="item.status&& visibleTitle=='查看任务'" class="select-option" :value="item.id" :label="item.smokeModel"> </lay-select-option>
                    <lay-select-option v-if="  visibleTitle!=='查看任务'" class="select-option" :value="item.id" :label="item.smokeModel"> </lay-select-option>
                  </template>

                  <lay-checkbox-group v-model="form_week.allowanceList" @change="check_change_week" :disabled="visibleTitle=='查看任务'">
                    <ul class="uu">
                      <template v-for="item in smokeList" :key="item.id">
                        <li v-if="item.status&& visibleTitle=='查看任务'" class="df" style="justify-content: left;">
                          <div style="flex: 1;">
                            <lay-checkbox name="like" skin="primary" :value="item.id" style=" padding: 8px 6px;" @click="check_click(item)">
                              <span>{{ item.smokeModel }}</span>
                            </lay-checkbox>
                          </div>
                          <div class="df weight ai-c" style="width: 200px;"> <span>烟支重量：</span> <el-input type="text" v-model="item.weight" placeholder="请输入重量/g"
                              :disabled="visibleTitle=='查看任务' || !item.status" /></div>
                          <div class="df data ai-c" style="margin: 0 10px;width: 200px;"> <span>生产日期：</span>

                            <!-- <el-input type="text" v-model="item.data" placeholder="格式2020-10-11" /> -->
                            <lay-date-picker v-model="item.data" simple type="date" placeholder="请选择" size="sm" :disabled="visibleTitle=='查看任务' || !item.status"></lay-date-picker>

                          </div>
                        </li>

                        <li v-if=" visibleTitle!=='查看任务'" class="df" style="justify-content: left;">
                          <div style="flex: 1;">
                            <lay-checkbox name="like" skin="primary" :value="item.id" style=" padding: 8px 6px;" @click="check_click(item)">
                              <span>{{ item.smokeModel }}</span>
                            </lay-checkbox>
                          </div>
                          <div class="df weight ai-c" style="width: 200px;"> <span>烟支重量：</span> <el-input type="text" v-model="item.weight" placeholder="请输入重量/g"
                              :disabled="visibleTitle=='查看任务' || !item.status" /></div>
                          <div class="df data ai-c" style="margin: 0 10px;width: 200px;"> <span>生产日期：</span>

                            <!-- <el-input type="text" v-model="item.data" placeholder="格式2020-10-11" /> -->
                            <lay-date-picker v-model="item.data" simple type="date" placeholder="请选择" size="sm" :disabled="visibleTitle=='查看任务' || !item.status"></lay-date-picker>

                          </div>
                        </li>
                      </template>
                    </ul>
                  </lay-checkbox-group>
                </lay-select>

              </div>
            </lay-form-item>

            <lay-form-item label="评吸人员" prop="userList">
              <!-- <lay-input v-model="form_week.userList"></lay-input> -->
              <lay-select v-model="form_week.userList" multiple placeholder="请选择" style="height: auto;width: 100%;" :minCollapsedNum="100" :disabled="visibleTitle=='查看任务'">
                <!-- <lay-select-option :value="item.id" :label="item.label" v-for="item in judgeList" :key="item.id"></lay-select-option> -->
                <template #header>
                  <div style="padding: 10px">
                    <lay-checkbox v-model="checkboxValue" skin="primary" :isIndeterminate="isIndeterminate" @change="hanldeChange" value="1" :disabled="visibleTitle=='查看任务'">全选</lay-checkbox>
                  </div>
                </template>
                <lay-select-option :value="item.name" :label="item.description" v-for="item in judgeData['1']" :key="item.name" :disabled="visibleTitle=='查看任务'"></lay-select-option>

              </lay-select>

              <!-- <lay-tree-select v-model="form_week.userList" :data="judgeData['1']" multiple :replaceFields="{ 	id: 'name', title: 'description', 	children: ''}"></lay-tree-select> -->

            </lay-form-item>
            <lay-form-item label="记录人" prop="recorder">
              <!-- <lay-input v-model="form_week.recorder"></lay-input> -->
              <lay-select v-model="form_week.recorder" placeholder="请选择" style="width: 100%;" :disabled="visibleTitle=='查看任务'">
                <lay-select-option :value="item.key" :label="item.title" v-for="item in userList1" :key="item.key"></lay-select-option>
              </lay-select>

            </lay-form-item>
            <lay-form-item label="负责人" prop="header">
              <!-- <lay-input v-model="form_week.header"></lay-input> -->
              <lay-select v-model="form_week.header" placeholder="请选择" style="width: 100%;" :disabled="visibleTitle=='查看任务'">
                <lay-select-option :value="item.key" :label="item.title" v-for="item in userList1" :key="item.key"></lay-select-option>
              </lay-select>
            </lay-form-item>
            <lay-form-item label="评吸时间" prop="meetingTime">
              <!-- <lay-input v-model="form_week.meetingTime"></lay-input> -->
              <lay-date-picker v-model="form_week.meetingTime" simple type="date" placeholder="请选择" style="width: 100%;" :disabled="visibleTitle=='查看任务'"></lay-date-picker>
            </lay-form-item>

          </lay-form>

        </div>
      </lay-layer>

      <el-dialog v-model="detailShow" :title="`${ isDayType? '日':'周'}评吸详情`" align="center" width="80vw">
        <div>
          <el-table :data="detailData" style="width: 100%" border height="50vh" :span-method="tableMerge" empty-text="暂无数据">
            <el-table-column prop="smokeName" label="品牌" width="180" align="center" />
            <el-table-column prop="userName" label="姓名" width="180" align="center" />
            <el-table-column prop="status" label="评吸状态" align="center">
              <template #default="{row}">
                <el-tag type="primary" v-if="row.status=='1'"> 已评吸 </el-tag>
                <el-tag type="info" v-else> 未评吸 </el-tag>
                <!-- <span>{{ row.status==1? '已评吸':'未评吸' }}</span> -->
              </template>
            </el-table-column>
            <el-table-column prop="conclusion" label="评吸描述" align="center" />
            <!-- <el-table-column prop="decision" label="判断" align="center">
              <template #default="{row}">
                <span>{{decisionType[row.determine]?.value || '-'}}</span>
              </template>
            </el-table-column> -->
          </el-table>
        </div>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="detailShow = false">关闭</el-button>
          </div>
        </template>
      </el-dialog>
    </div>

  </div>
</template>
  
  <script setup lang="ts">
import { layer } from "@layui/layui-vue";
import ManagerTable from "@/components/ManagerTable.vue";
import http from "@/http/index";
import { onMounted, ref, Ref, nextTick, reactive, watch, watchEffect } from "vue";
import Pagination from "@/components/pagination.vue";
import { ElMessage } from "element-plus";
import type { TableColumnCtx } from "element-plus";
// import { number } from "echarts";

const check_change_week = (e) => {
  console.log(smokeList.value);
  selectData.value = [];
  console.log(e);

  nextTick(() => {
    if (e) {
      smokeList.value.forEach((item) => {
        if (form_week.allowanceList) {
          e.forEach((ele) => {
            if (item.id == ele) {
              selectData.value.push(item);
            }
          });
        }
      });
    }

    console.log(selectData.value);
  });
};
const check_click = (item) => {
  console.log(item);

  item.status = !item.status;
};
const isIndeterminate = ref(false);
const checkboxValue = ref(false);
const isIndeterminate_d = ref(false);
const checkboxValue_d = ref(false);

const hanldeChange = (v) => {
  isIndeterminate.value = false;
  form_week.userList = [];
  console.log(v);
  if (v) {
    judgeData.value["1"].forEach((item) => {
      form_week.userList.push(item.name);
    });
  } else {
    form_week.userList = [];
  }
};
const hanldeChange_d = (v) => {
  isIndeterminate_d.value = false;
  form.value.userList = [];
  console.log(v);
  if (v) {
    judgeData.value["0"].forEach((item) => {
      form.value.userList.push(item.name);
    });
  } else {
    form.value.userList = [];
  }
};

function isValidDateFormat(dateString) {
  // 使用正则表达式来匹配日期格式
  const regex = /^\d{4}-\d{2}-\d{2}$/;
  if (!regex.test(dateString)) {
    return false; // 如果不匹配，返回false
  }

  // 分割日期字符串
  const parts = dateString.split("-");
  const year = parseInt(parts[0], 10);
  const month = parseInt(parts[1], 10);
  const day = parseInt(parts[2], 10);

  // 检查月份和日期是否在合理范围内
  if (month < 1 || month > 12) {
    return false;
  }
  if (day < 1 || day > 31) {
    return false;
  }

  // 注意：这里并没有检查日期是否真实存在（例如，2月30日是不存在的）
  // 如果需要更严格的检查，可以使用 Date 对象来尝试解析日期

  // 尝试使用 Date 对象来验证日期
  const date = new Date(year, month - 1, day); // 注意：月份在 Date 对象中是0-based
  return date.getFullYear() === year && date.getMonth() + 1 === month && date.getDate() === day;
}

// 周评吸  确认 取消操作
const visible_opteron_week = ref([
  {
    text: "确认",
    callback: async () => {
      console.log(elFormRef11.value);
      console.log(selectData.value);

      let isFlag = true;
      selectData.value.forEach((item) => {
        // || item.weight.includes(".")
        if (!item.weight || !item.data || !isValidDateFormat(item.data) || item.weight <= 0) {
          layer.msg("请检车烟支重量/生产日期格式是否正确", { icon: 2, time: 2500 });
         
        }
        if (!isNumberWithMaxThreeDecimalPlaces(item.weight)) {
          layer.msg("烟支重量格式不对并且最多保留三位小数", { icon: 2, time: 2500 });
          isFlag = false;
        }
      });

      if (!isFlag) return false;

      elFormRef11.value.validate(async (isValidate, model, errors) => {
        console.log(isValidate, model, errors);
        if (isValidate) {
          let data: any = {
            allowanceList: [],
            header: form_week.header,
            recorder: form_week.recorder,
            userList: form_week.userList,
            meetingTime: form_week.meetingTime + " 00:00:00",
            type: "1",
          };
          selectData.value.forEach((item) => {
            data.allowanceList.push({ id: item.id, weight: item.weight, date: item.data });
          });
          console.log(form_week.userList);

          // let uniqueUserNames = new Set();
          // form_week.userList.forEach((item) => {
          //   console.log(item);
          //   console.log(judgeData.value[item]);
          //   judgeData.value[item].forEach((element) => {
          //     uniqueUserNames.add(element.name); //
          //   });
          // });

          // // 将 Set 中的唯一用户名转换为数组，并赋值给 data.userList
          // data.userList = Array.from(uniqueUserNames);

          console.log(data);

          const res = await http.corsApi("/taskDetail/add", "post", { ...data });
          console.log(res);
          if (res.data) {
            layer.msg("新增成功", { icon: 1, time: 1500 });
            is_visible_week.value = false;

            await get_list(pageNo.value, pageSize.value);
          }
        }
      });
    },
  },
  {
    text: "取消",
    callback: () => {
      is_visible_week.value = false;
    },
  },
]);
// 烟支重量校验
function isNumberWithMaxThreeDecimalPlaces(value) {
  // 首先检查是否是数值类型
  // if (typeof value !== 'number') {
  //     return false;
  // }
  if (isNaN(value)) {
    return false;
  }

  // 转换为字符串以便使用正则表达式进行检查
  const strValue = value.toString();

  // 使用正则表达式检查是否最多有三位小数
  const regex = /^(?!\.0+$)\d+(\.\d{1,3})?$/;
  return regex.test(strValue);
}

const elFormRef11 = ref();
const form_week = reactive({
  allowanceList: [],
  header: "",
  recorder: "",
  userList: [],
  meetingTime: "",
});
const selectData = ref([]);
const judgeList = ref([]);
const judgeData = ref([]);
const getjudgeList = async () => {
  const res = await http.corsApi("/secUser/judgeList", "get", {});
  console.log(res);
  if (res.data) {
    judgeData.value = res.data;

    // for (const ele in res.data) {
    //   console.log(ele);
    //   judgeList.value.push({
    //     label: ele == 0 ? "日评委" : ele == 1 ? "周评委" : "月评委",
    //     id: ele,
    //   });
    // }

    // console.log(judgeList.value);
  }
};
getjudgeList();

watch(form_week.userList, (val) => {
  console.log(val);

  // if (val.length === 0) {
  //   checkboxValue.value = false
  //   isIndeterminate.value = false
  // } else if (val.length === 3) {
  //   checkboxValue.value = true
  //   isIndeterminate.value = false
  // } else {
  //   checkboxValue.value = true
  //   isIndeterminate.value = true
  // }
});

const validateAllowanceList = (rule: any, value: any, callback: any) => {
  console.log(value);

  if (value === "") {
    callback(new Error("烟支不能为空"));
  } else {
    // if (ruleForm.checkPass !== '') {
    //   if (!ruleFormRef.value) return
    //   ruleFormRef.value.validateField('checkPass', () => null)
    // }
    // callback();
    selectData.value.forEach((item) => {
      console.log(item);
      if (!item.weight || !item.data) {
        console.log(item);
        callback(new Error(`请检查输入是否完整`));
      } else {
        return true;
      }
    });
  }
};
const rules_week = ref({
  // allowanceList: [{ validator: validateAllowanceList, trigger: ["click", "blur", "change"], required: true }],
  // header: [{ required: true, message: "负责人不能为空", trigger: "blur" }],
  // recorder: [{ required: true, message: "记录人 input Activity name", trigger: "blur" }],
  // meetingTime: [{ required: true, message: "评吸时间 input Activity name", trigger: "blur" }],
  // userList: [{ required: true, message: "评吸人员 input Activity name", trigger: "blur" }],
  // allowanceList: {
  //   validator(rule, value, callback, source, options) {
  //     console.log(form_week.allowanceList);
  //     console.log(value);
  //     nextTick(()=>{
  //       selectData.value.forEach((item) => {
  //       console.log(item);
  //       if (!item.weight ||!item.data ) {
  //         console.log(item);
  //         callback(new Error(`请检查输入是否完整`));
  //       } else {
  //         return true;
  //       }
  //     });
  //     })
  //   },
  // },
});

// tab切管
const task_tab_change = async (e) => {
  console.log(e);
  listType.value = e;
  await get_list(pageNo.value, pageSize.value);
};

function get_smoke_name(id) {
  // console.log(id);
  for (const ele of smokeList.value) {
    // console.log(ele);
    if (ele.id == id) {
      return ele.smokeModel;
    }
  }
}
function get_user_name(id) {
  console.log(id);
  for (const ele of userList1.value) {
    console.log(ele);
    if (ele.key == id) {
      return ele.title;
    }
  }
}

interface FormType {
  allowanceList: any;
  meetingTime: string;
  name: string;
  number: string;
  orgId: 0;
  produceTime: string;
  smokeWeight: string;
  status: string;
  type: string;
  userList: any;
}
// 上方查询配置
const titleOption = ref({
  name1: "任务名称",
  name2: "任务时间",
  btn1: "查询",
  btn2: "重置",
  btn3: "导出",
  name2Type: "time",
  name1Show: "0",
  name2DateNone: true,
});
// 表格上方配置
const tableTopBtn = ref([
  {
    name: "新增日任务",
    type: "primary",
    clickType: "add",
    id: "1",
    btnPer: "task_add",
  },
  {
    name: "新增周任务",
    type: "primary",
    clickType: "add_week",
    id: "11",
    btnPer: "task_add_week",
  },
  //   {
  //     name: "修改",
  //     type: "primary",
  //     clickType: "edit",
  //     id: "2",
  //   },
  //   {
  //     name: "删除",
  //     type: "danger",
  //     clickType: "del",
  //     id: "3",
  //   },
]);
// table 右侧配置
const tableRBtn = ref([
  {
    name: "发布",
    type: "normal",
    clickType: "push",
    id: "6",
    disabled: { status: ["1"] },
    btnPer: "task_issue",
  },
  {
    name: "修改",
    type: "primary",
    clickType: "edit",
    id: "1",
    disabled: { status: ["1"] },
    btnPer: "task_edit",
  },
  {
    name: "删除",
    type: "danger",
    clickType: "del",
    id: "2",
    disabled: { status: ["1"] },
    btnPer: "task_delete",
  },
  {
    name: "查看",
    type: "",
    clickType: "view",
    id: "3",
    btnPer: "task_view",
  },
  {
    name: "详情",
    type: "",
    clickType: "detail",
    id: "5",
    btnPer: "task_detail",
  },

  {
    name: "导出",
    type: "",
    clickType: "export",
    id: "4",
    disabled: { status: ["1"] },
    btnPer: "task_export",
  },
]);

// 弹层控制
const is_visible = ref(false);
// 弹层表单
const form = ref({
  allowanceList: [],
  meetingTime: "",
  name: "",
  number: "",
  orgId: "",
  produceTime: "",
  smokeWeight: "",
  status: "0",
  type: "",
  userList: [],
});
const rules = ref({
  smokeWeight: {
    validator(rule, value, callback, source, options) {
      if (Number.isNaN(value * 1)) {
        callback(new Error(`请正确填写烟支重量`));
      } else {
        return true;
      }
    },
  },
});
const allowance_id = ref("");

const smoke_change = (val) => {
  console.log(val);
  form.value.allowanceList = [val];
};

// 牌号  津贴
const search1 = ref("");
const search2 = ref("");

// 任务类型change时间
const type_change = () => {
  console.log(111);
  // form.value.allowanceList = [];
  // allowance_id.value = "";
};

const layFormRef11 = ref();
// 弹层title
const visibleTitle = ref("");
// 弹层按钮
const visible_opteron = ref([
  {
    text: "确认",
    callback: async () => {
      console.log(121);
      // if (form.value.type == "1") {
      //   form.value.meetingTime = form.value.produceTime;
      // }

      if (Number.isNaN(form.value.smokeWeight * 1)) {
        layer.msg("请检查重量填写是否有误", { icon: 2, time: 2000 });
        return false;
      }

      layFormRef11.value.validate(async (isValidate, model, errors) => {
        console.log(isValidate, model, errors);
        if (isValidate) {
          // if (form.value.type == "1") {
          //   form.value.allowanceList = [allowance_id.value];
          // }

          //   if (form.value.smokeModel == "" || form.value.smokePerk == "") {
          //     layer.msg("请检查输入收否完整", { time: 1500, icon: 2 });
          //     return false;
          //   }
          let data: any = {
            type: "0",
            meetingTime: form.value.meetingTime + " 00:00:00",
            userList: form.value.userList,
            allowanceList: [],
          };
          let tip = "添加";
          let methods = "post";
          form.value.allowanceList.forEach((item) => {
            data.allowanceList.push({ id: item, data: "", time: "" });
          });

          // let uniqueUserNames = new Set();
          // form.value.userList.forEach((item) => {
          //   console.log(item);
          //   console.log(judgeData.value[item]);
          //   judgeData.value[item].forEach((element) => {
          //     uniqueUserNames.add(element.name); //
          //   });
          // });

          // // 将 Set 中的唯一用户名转换为数组，并赋值给 data.userList
          // data.userList = Array.from(uniqueUserNames);

          // else if (visibleTitle.value == "修改任务") {
          //   data = { ...form.value, id: tableID.value };
          //   tip = "修改任务";
          //   methods = "put";
          // }
          // data.meetingTime = data.meetingTime + " 00:00: 00";
          console.log(form.value);

          console.log(data);

          const res = await http.corsApi("/taskDetail/add", methods, data);
          console.log(res);
          if (res.data) {
            await get_list(pageNo.value, pageSize.value);
            layer.msg(tip + "成功", { icon: 1 });
            is_visible.value = false;
          }
        }
      });
    },
  },
  {
    text: "取消",
    callback: () => {
      is_visible.value = false;
      //   layer.confirm("取消操作", { shade: false,icon:2 });
    },
  },
]);

/********** 评吸详情 ********/
let detailShow: Ref<Boolean> = ref(false);
let detailData: Ref<Array<any>> = ref([]);
let isDayType: Ref<Boolean> = ref(false);
let decisionType: any = {
  0: { value: "正常" },
  1: { value: "不正常" },
  2: { value: "基本正常" },
};
let smokeMap = new Map(); //表示有多少种烟

// { row: any, column: any, rowIndex: number, columnIndex: number }
// function tableMerge({}:TableColumnCtx) {}
function tableMerge({ row, rowIndex, columnIndex }: any) {
  if (columnIndex === 0) {
    let value = row.smokeName;
    let sum: number = smokeMap.get(value) || 1; //表示有多少个相同的
    if (rowIndex === 0) {
      // 第一个一定会显示
      return {
        rowspan: sum,
        colspan: 1,
      };
    } else if (rowIndex == detailData.value.length - 1) {
      //最后一个元素在人数不为1时需要被合并
      return {
        rowspan: sum === 1 ? 1 : 0,
        colspan: sum === 1 ? 1 : 0,
      };
    }
    let pre = detailData.value[rowIndex - 1]; //当前元素前一个元素
    if (pre.smokeName !== value) {
      //表示当前烟类的第一个
      return {
        rowspan: sum,
        colspan: 1,
      };
    } else {
      return {
        rowspan: sum === 1 ? 1 : 0,
        colspan: sum === 1 ? 1 : 0,
      };
    }
  }
}

// 表格配置
const columns = ref([
  // {
  //   title: "任务ID",
  //   key: "id",
  // },
  {
    title: "任务名称",
    key: "name",
  },
  {
    title: "任务类型",
    key: "type",
    customSlot: "taskType",
  },
  {
    title: "创建时间",
    key: "createday",
  },
  // {
  //   title: "评吸状态",
  //   key: "status",
  //   customSlot: "taskstatus",
  // },
  {
    title: "创建人",
    key: "creator",
  },
  {
    title: "操作",
    customSlot: "taskoperator",
    key: "taskoperator",
  },
]);
const dataSource = ref([]);
const pageNo = ref(1);
const pageSize = ref(10);
// 当前点击的id
const tableID = ref("");
// 表格操作按钮
const tableRClick = async (item: any, row: any) => {
  console.log(item, row);
  if (item.clickType === "edit") {
    await get_user_list();
    await get_smoke_list();
    await get_detail(row.id);
    await get_org_list_tree();
    visibleTitle.value = "修改任务";
    is_visible.value = true;
    tableID.value = row.id;
    // form.value = row;
  } else if (item.clickType === "view") {
    visibleTitle.value = "查看任务";
    await get_user_list();
    await get_smoke_list();
    await get_detail(row.id);
    await get_org_list_tree();
    if (row.type == "0") {
      is_visible.value = true;
    } else {
      is_visible_week.value = true;
    }

    tableID.value = row.id;
  } else if (item.clickType === "detail") {
    showDetail(row);
  } else if (item.clickType === "push") {
    pushTash(row);
  }

  if (item.clickType === "del") {
    layer.confirm("确认要删除吗？", {
      btn: [
        {
          text: "确认",
          callback: async (id) => {
            const res = await http.corsApi("/task/batch", "delete", [row.id]);
            console.log(res);
            if (res.data) {
              await get_list(pageNo.value, pageSize.value);
              await layer.confirm("删除成功", { icon: 1 });
            }
            layer.close(id);
          },
        },
        {
          text: "取消",
          callback: (id) => {
            layer.close(id);
          },
        },
      ],
    });
  }

  // 导出
  if (item.clickType === "export") {
    console.log(item, row);

    let url = "";
    if (listType.value == "0") {
      url = "/taskDetail/exportDayAllUserFile";
    } else if (listType.value == "1") {
      url = "/taskDetail/exportWeekFile";
    }

    const res = await http.corsApi(`${url}/${row.id}`, "get", {}, { is_msg: false, formData: true });

    console.log("导出测试？？？？？？？？？？？？？", res);

    if (res.data) {
      // res 为后端返回的响应对象
      // let blob = new Blob([res]);
      try {
        let url = window.URL.createObjectURL(res.data);
        let a = document.createElement("a");
        a.href = url;
        a.download = decodeURI(res.headers["content-disposition"])?.split("filename=")[1]?.replace(/"/g, "") || new Date().getTime() + ".zip";
        a.click();
        window.URL.revokeObjectURL(url);
        layer.msg("导出成功", { icon: 1, time: 2000 });
      } catch (err) {
        console.log(err);
      }
    }
  }
};

async function showDetail(row: any) {
  // 是否未日评吸
  isDayType.value = row.type == "0";
  const res: any = await http.corsApi(`/task/findInfo?taskId=${row.id}`, "get", {});
  console.log("获取到的详情数据", res);
  if (res.code != 200) {
    return;
  }
  let { data } = res;
  smokeMap = new Map();
  if (Array.isArray(data)) {
    detailData.value = data;
    data.forEach((ele) => {
      //遍历数组查看每种烟的提交人数
      let total = 0;
      if (smokeMap.has(ele.smokeName)) {
        total = smokeMap.get(ele.smokeName);
      }
      smokeMap.set(ele.smokeName, total + 1);
    });
  } else {
    //没什么用，为了适配之前的数据格式
    detailData.value = [];
    Object.keys(data).forEach((key: string) => {
      let list = data[key];
      smokeMap.set(key, list.length);
      list.forEach((ele: any) => {
        detailData.value.push({ ...ele });
      });
    });
  }

  detailData.value.sort((a, b) => {
    // 使用 localeCompare 进行本地化敏感的字符串比较
    return a.smokeName.localeCompare(b.smokeName);
  });
  console.log(detailData.value);
  detailShow.value = true;
}

async function pushTash(row: any) {
  console.log(row);
  const res: any = await http.corsApi(`/task/${row.id}`, "get", {});
  let form = res.data;
  form.status = "1";
  const result: any = await http.corsApi(`/task/publish`, "put", form);
  if (result.code == 200) {
    ElMessage.success("发布成功");
    get_list(pageNo.value, pageSize.value);
  }
}

const is_visible_week = ref(false);
// 表格上方按钮
const tableTopClick = async (item) => {
  console.log(search1.value, search2.value);

  if (item.clickType === "add") {
    visibleTitle.value = "新增日任务";
    await get_user_list();
    await get_smoke_list();
    await get_org_list_tree();
    is_visible.value = true;
    form.value = {
      allowanceList: [],
      meetingTime: "",
      name: "",
      number: "",
      orgId: "",
      produceTime: "",
      smokeWeight: "",
      status: "0",
      type: "",
      userList: [],
    };
  } else if (item.clickType === "add_week") {
    form_week.allowanceList = [];
    form_week.header = "";
    form_week.recorder = "";
    form_week.userList = [];
    form_week.meetingTime = "";
    visibleTitle.value = "新增周任务";
    console.log(item);
    is_visible_week.value = true;
    await get_smoke_list();
    await get_user_list();
  }
};

/**批量导出 */
async function export_table() {
  let params = {
    taskName: search1.value,
    beginTime: search2?.value[0] || "",
    endTime: search2?.value[1] || "",
    type: listType.value, // 0为日 1为周
  };
  console.log("导出功能", params);
  let url = `/taskDetail/exportDayAll`;
  if (params.type == "1") {
    url = `/taskDetail/exportWeekAll`;
  }

  const res = await http.corsApi(url, "get", params, { is_msg: false, formData: true });
  console.log("导出结果为", res);

  if (res.data) {
    // res 为后端返回的响应对象
    // let blob = new Blob([res]);
    let url = window.URL.createObjectURL(res.data);
    let a = document.createElement("a");
    a.href = url;
    a.download = decodeURI(res.headers["content-disposition"])?.split("filename=")[1]?.replace(/"/g, "") || new Date().getTime() + ".zip";
    a.click();
    window.URL.revokeObjectURL(url);
    layer.msg("导出成功", { icon: 1, time: 2000 });
  }
}

// 查询
// 查询
const search_btn = async (e) => {
  console.log(e);

  await get_list(pageNo.value, pageSize.value);
};
// 重置
const resert = async () => {
  search1.value = "";
  search2.value = "";
  await get_list(pageNo.value, pageSize.value);
};

// 分页
const limit = ref(10);
const total = ref(0);
const currentPage = ref(1);
// 分页事件
const page_change = async (page, limt) => {
  console.log(page, limt);
  currentPage.value = page;
  pageNo.value = page;

  await get_list(page, limt);
};
// 日评吸  周评吸
const listType = ref("0");
const get_list = async (page: number | string, pagesize: number | string) => {
  const res = await http.corsApi("/task/page", "get", {
    pageNo: page,
    pageSize: pagesize,
    name: search1.value,
    // meetingTime: search2.value,
    beginTime: search2?.value[0] || "",
    endTime: search2?.value[1] || "",
    type: listType.value,
  });

  console.log(res);
  dataSource.value = res.data.list;
  total.value = res.data.totalCount;
};

const userList1 = ref([]);
// 获取用户列表
const get_user_list = async () => {
  const res = await http.corsApi("/secUser/getUserList", "get", {});
  console.log(res);
  userList1.value = res.data;
};

// 获取牌号    烟支  /smokeAllowance
const smokeList = ref([]);
// 获取用户列表
const get_smoke_list = async () => {
  const res = await http.corsApi("/smokeAllowance", "get", {});
  console.log(res);
  smokeList.value.forEach((item) => {
    item["weight"] = "";
    item["data"] = "";
    item["smokeId"] = "";
    item["status"] = false;
  });

  smokeList.value = res.data;
};

const get_detail = async (id) => {
  const res = await http.corsApi(`/task/${id}`, "get", {});

  console.log(res.data);
  console.log(judgeData.value["1"]);

  // form.value = res.data;

  allowance_id.value = res.data.allowanceList ? res.data.allowanceList[0] : "";
  // form.value.status = '1'

  try {
    if (listType.value == "1") {
      form_week.userList = res.data.userList;
      form_week.recorder = res.data.recorder;
      form_week.header = res.data.header;
      form_week.meetingTime = res.data.meetingTime.split(" ")[0];

      form_week.allowanceList = [];
      // smokeList.value.forEach((item) => {
      //   for (const ele of res.data.allowanceList) {
      //     console.log(ele);

      //     if (item.id == ele.id) {
      //       item.weight = ele.weight;
      //       item.data = ele.date;
      //       item['status'] = true
      //       form_week.allowanceList.push(item.id);
      //     }
      //   }
      // });
    } else {
      form.value.allowanceList = [];
      form.value.meetingTime = res.data.meetingTime.split(" ")[0];
      form.value.userList = res.data.userList;
      res.data.allowanceList.forEach((item) => {
        form.value.allowanceList.push(Number(item.id));
      });
    }
    smokeList.value.forEach((item) => {
      for (const ele of res.data.allowanceList) {
        console.log(ele);

        if (item.id == ele.id) {
          item.weight = ele.weight;
          item.data = ele.date;
          item["status"] = true;
          form_week.allowanceList.push(item.id);
        }
      }
    });
  } catch (err) {
    console.log(err);
  }
  console.log(smokeList.value);

  console.log(form.value);
};

const orgList = ref([]);
// 获取部门列表
const get_org_list_tree = async () => {
  // const res = await http.corsApi("/secOrg/getOrgAllTreeData", "get", {});
  const res = await http.corsApi("/secOrg", "get", {});
  console.log(res);
  orgList.value = res.data;
};

// 页面初始化、
onMounted(() => {
  get_list(pageNo.value, pageSize.value);
});

watchEffect(async () => {
  console.log(form_week.userList);
  console.log(judgeData.value["1"]);
  try {
    if (form_week.userList.length == judgeData.value["1"]?.length) {
      checkboxValue.value = true;
    } else {
      checkboxValue.value = false;
    }
    if (form.value.userList.length == judgeData.value["0"]?.length) {
      checkboxValue_d.value = true;
    } else {
      checkboxValue_d.value = false;
    }
  } catch (err) {
    console.log(err);
  }
});
</script>
  
  <style scoped lang="scss">
.week-visible {
  .select-option {
    display: none;
    :deep(.layui-select-content) {
      color: #fff;
      dd {
        display: none;
      }
    }
  }
}

.layui-select-content {
  .uu {
    li {
      display: flex;
      justify-content: space-between;
      width: 100%;
      > span {
        width: 300px;
      }
      .weight {
        width: 700px;
      }
      .data {
        width: 700px;
      }
      > div {
        span {
          white-space: nowrap;
        }
      }
    }
  }
}
.layui-select-content .select-option {
  display: none;
}
</style>